package com.folderit.apps.rooms;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;

import com.folderit.apps.rooms.data.RoomsContract.RoomEntry;

import java.util.Calendar;

/**
 * Created by César on 22/12/2014.
 */
public class CreateEditReservationFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
    private static final String LOG_TAG = CreateEditReservationFragment.class.getName();

    private int mSelectedRoomId;

    private static final String SELECTED_ROOM = "selected_room";
    // TODO: Here I need to store every value entered on the form?

    //private static final int RESERVATIONS_LOADER = 0;

    // For the reservation view we're showing only a small subset of the stored data.
    // Specify the columns we need.
    private static final String[] ROOM_COLUMS = {
            RoomEntry._ID,
            RoomEntry.COLUMN_ROOM_NAME,
            RoomEntry.COLUMN_DESCRIPTION
    };

    // These indices are tied to RESERVATION_COLUMNS.
    // If RESERVATION_COLUMNS changes, these must change.
    public static final int COL_ROOM_ID = 0;
    public static final int COL_ROOM_NAME = 1;
    public static final int COL_DESCRIPTION = 2;

    private Spinner mRoomSpinner;
    private EditText mEventTitle;
    private EditText mBeginDate;
    private EditText mBeginTime;
    private EditText mEndDate;
    private EditText mEndTime;
    private Button mButtonDone;

    public CreateEditReservationFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Add this line in order for this fragment to handle menu events.
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.reservationsfragment, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_new_reservation) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Get the selected room id from arguments
        Bundle arguments = getArguments();
        if (arguments != null) {
            mSelectedRoomId = arguments.getInt(CreateEditReservationActivity.SELECTED_ROOM_NEW_RESERVATION_KEY);
        }

        View rootView = inflater.inflate(R.layout.fragment_create_edit_reservation, container, false);
        mRoomSpinner = (Spinner) rootView.findViewById(R.id.create_edit_room_spinner);
        mEventTitle = (EditText) rootView.findViewById(R.id.create_edit_event_title_edittext);
        //mBeginDate = (EditText) rootView.findViewById(R.id.create_edit_begin_date_edittext);
        mBeginTime = (EditText) rootView.findViewById(R.id.create_edit_begin_time_edittext);
        mEndDate = (EditText) rootView.findViewById(R.id.create_edit_end_date_edittext);
        mEndTime = (EditText) rootView.findViewById(R.id.create_edit_end_time_edittext);
        mButtonDone = (Button) rootView.findViewById(R.id.create_edit_done_button);
        mButtonDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO: 1. Validate info - 2. Send info to the server
            }
        });

        ((Button)rootView.findViewById(R.id.change_date_button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTimePickerDialog(view);
            }
        });

        // If there's instance state, mine it for useful information.
        // Here I need to put again the data was stored if (for example)
        // the user rotate his device.
        if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_ROOM)) {
            // TODO: fill up all the views with its previous values.
        }

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        // Get the selected room id
        if (savedInstanceState != null) {
            mSelectedRoomId = savedInstanceState.getInt(ReservationsActivity.SELECTED_ROOM_KEY);
        }

        //getLoaderManager().initLoader(RESERVATIONS_LOADER, null, this);
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();

        Bundle arguments = getArguments();
        if (arguments != null && arguments.containsKey(ReservationsActivity.SELECTED_ROOM_KEY)) {
            //getLoaderManager().restartLoader(RESERVATIONS_LOADER, null, this);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // Store the selected room
        if (mSelectedRoomId != 0) {
            outState.putInt(ReservationsActivity.SELECTED_ROOM_KEY, mSelectedRoomId);
        }

        super.onSaveInstanceState(outState);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) { }

    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getActivity().getSupportFragmentManager(), "timePicker");
    }

    public static class TimePickerFragment extends DialogFragment
            implements TimePickerDialog.OnTimeSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current time as the default values for the picker
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            return new TimePickerDialog(getActivity(), this, hour, minute,
                    DateFormat.is24HourFormat(getActivity()));
        }

        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            // Do something with the time chosen by the user
        }
    }

    public static class DatePickerFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
        }
    }
}


